< previous page page_421 next page >

Page 421
The preceding lines of code check the PrevInstance property of the App object and end the program if another instance is already running. Although this code prevents conflicts and errors, it does not help the users because they still have to find the other application window manually. With a few additional API calls, you can have your program show the previous application before exiting. Listing 18.2 shows a simple routine to display the previous instance before exiting.
Listing 18.2 PREVINST.ZIPHandling Multiple Application Instances
Option Explicit
Private Declare Function FindWindow Lib "user32" Alias "FindWindowA" _
                         (ByVal lpClassName As String, ByVal lpWindowName _
                         As String) As Long
Private Declare Function ShowWindow Lib "user32" (ByVal hwnd As Long, _
                         ByVal nCmdShow As Long) As Long
Private Declare Function SetForegroundWindow Lib "user32" (ByVal hwnd As Long) _
                         As Long
Private Const SW_RESTORE = 9

Private Sub Form_Load()
    Dim sTitle As String
    Dim hwnd As Long
    Dim lRetVal As Long

    If App.PrevInstance Then
        sTitle = Me.Caption

        App.Title = "newcopy"
        Me.Caption = "newcopy"

        hwnd = FindWindow(vbNullString, sTitle)
        If hwnd <> 0 Then
            lRetVal = ShowWindow(hwnd, SW_RESTORE)
            lRetVal = SetForegroundWindow(hwnd)
        End If
        End
    End If

End Sub
In the preceding code, you first rename the current application's title and form caption properties so that the FindWindow API function cannot find it. Then you use three API calls to find the window belonging to the previous application, restore it, and move it to the foreground. The Windows API functions are discussed in more detail in Chapter 20, "Accessing the Windows API."
note.gif The methods for dealing with multiple instances described here pertain to a Standard EXE project. ActiveX DLLs are discussed in Chapter 16, "Classes: Reusable Components." square.gif

sarrow.gifSee "Setting the Instancing Property," p. 371

 
< previous page page_421 next page >